#include "serverswindow.h"
#include "ui_serverswindow.h"

ServersWindow::ServersWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ServersWindow)
{
    ui->setupUi(this);

    this->m_path = QDir::cleanPath(QCoreApplication::applicationDirPath());
    initUI();
}

ServersWindow::~ServersWindow()
{
    delete ui;
}

//初始化
void ServersWindow::initUI()
{
    //初始化右键菜单
    this->m_menu = new QMenu(this);
    this->m_menu->addAction(ui->actionNewServer);
    this->m_menu->addAction(ui->actionEditServer);
    this->m_menu->addAction(ui->actionDelServer);
    this->m_menu->addAction(ui->actionFileTransfer);

    ui->lvServers->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->lvServers, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(on_lvServersPopContextMenu(QPoint)));
    ui->lvServers->setEditTriggers(QAbstractItemView::NoEditTriggers);          //不可编辑
    ui->lvServers->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->lvServers->setModel(&this->m_servers);

    //加载服务器列表
    QList<ModelServer> servers = this->loadServers();
    for(int i=0;i<servers.count();i++)
    {
        this->addServerToModel(servers[i]);
    }
}

void ServersWindow::saveServers()
{
    QString fileName = this->m_path+"/servers.lst";

    QFile file(fileName);
    if(file.open(QIODevice::WriteOnly))
    {
        QJsonDocument jdoc;
        QJsonArray jarr;

        if(this->m_servers.rowCount()>0)
        {
            for(int i=0;i<this->m_servers.rowCount();i++)
            {
                QStandardItem* item = this->m_servers.item(i);
                ModelServer data = item->data(Qt::UserRole).value<ModelServer>();

                QJsonObject jitem;
                jitem.insert("id",data.id);
                jitem.insert("name",data.serverName);
                jitem.insert("dest",data.serverDest);
                jitem.insert("port",data.serverPort);
                jitem.insert("username",data.userName);
                jitem.insert("passwd",data.passWd);
                jarr.append(jitem);
            }
        }

        jdoc.setArray(jarr);

        QByteArray bdata = jdoc.toJson();
        file.write(bdata);
        file.flush();
    }
    else
    {
        QMessageBox::critical(this, tr("提示"),tr("文件打开失败~"));
    }
}

//加载列表
QList<ModelServer> ServersWindow::loadServers()
{
    QList<ModelServer> res;
    QString fileName = this->m_path+"/servers.lst";

    QFile file(fileName);
    if(file.open(QIODevice::ReadOnly))
    {
        QByteArray bdata = file.readAll();
        if(bdata.length()>0)
        {
            QJsonDocument jdoc = QJsonDocument::fromJson(bdata);
            QJsonArray jarr = jdoc.array();

            for(int i=0;i<jarr.count();i++)
            {
                QJsonObject jobj = jarr.at(i).toObject();

                ModelServer item;
                item.id = jobj["id"].toString();
                item.serverName = jobj["name"].toString();
                item.serverDest = jobj["dest"].toString();
                item.serverPort = jobj["port"].toInt();

                //新增字段可能为空
                if(jobj.contains("username"))
                    item.userName = jobj["username"].toString();
                else
                    item.userName = "";
                if(jobj.contains("passwd"))
                    item.passWd = jobj["passwd"].toString();
                else
                    item.passWd = "";

                res.append(item);
            }
        }
    }

    return res;
}

//添加一个实体到模型中
void ServersWindow::addServerToModel(ModelServer info)
{
    QStandardItem* mitem = new QStandardItem(info.serverName);
    QVariant data;
    data.setValue(info);
    mitem->setData(data, Qt::UserRole);

    this->m_servers.appendRow(mitem);
}

//显示菜单
void ServersWindow::on_lvServersPopContextMenu(QPoint p)
{
    QModelIndexList indexes = ui->lvServers->selectionModel()->selectedIndexes();

    bool isenable = true;
    if(indexes.length() > 0)
        isenable = true;
    else
        isenable = false;

    ui->actionEditServer->setEnabled(isenable);
    ui->actionDelServer->setEnabled(isenable);

    this->m_menu->exec(QCursor::pos());
}

//新建/编辑返回
void ServersWindow::on_NewServerCallback(bool isNew, ModelServer info)
{
    if(isNew){
        //如果是新增
        this->addServerToModel(info);
    }else{
        //如果是编辑
        QModelIndexList indexes = ui->lvServers->selectionModel()->selectedIndexes();
        QStandardItem* item = this->m_servers.item(indexes[0].row(),0);

        //更新值
        QVariant data;
        data.setValue(info);
        item->setData(data, Qt::UserRole);

        //更新显示
        item->setText(info.serverName);
    }

    //保存到文件
    this->saveServers();

    ui->lvServers->update();
}

//显示添加服务器对话框
void ServersWindow::on_actionNewServer_triggered()
{
    DiaNewServer dia(this, nullptr);
    connect(&dia, SIGNAL(signalAccepted(bool,ModelServer)),
            this, SLOT(on_NewServerCallback(bool,ModelServer)));
    dia.setWindowTitle(tr("新增"));
    dia.setPort("20011");                               //默认端口
    dia.exec();
}

//显示编辑对话框
void ServersWindow::on_actionEditServer_triggered()
{
    //找到当前选中项
    QModelIndexList indexes = ui->lvServers->selectionModel()->selectedIndexes();
    if(indexes.length() > 0)
    {
        QStandardItem* item = this->m_servers.item(indexes[0].row(),0);
        ModelServer info = item->data(Qt::UserRole).value<ModelServer>();

        DiaNewServer dia(this, &info);
        connect(&dia, SIGNAL(signalAccepted(bool,ModelServer)),
                this, SLOT(on_NewServerCallback(bool,ModelServer)));

        dia.setWindowTitle(tr("编辑"));
        dia.exec();
    }
}

//双击打开
void ServersWindow::on_lvServers_doubleClicked(const QModelIndex &index)
{
    QStandardItem* item = this->m_servers.item(index.row(), 0);
    ModelServer info = item->data(Qt::UserRole).value<ModelServer>();

    if(this->m_mainWins.contains(info.id))
    {
        this->m_mainWins[info.id]->show();
    }
    else
    {
        MainWindow* win = new MainWindow(this);
        this->m_mainWins.insert(info.id, win);
        win->connectToServer(info);
        win->show();
    }
}

//删除服务器
void ServersWindow::on_actionDelServer_triggered()
{
    //找到当前选中项
    QModelIndexList indexes = ui->lvServers->selectionModel()->selectedIndexes();
    if(indexes.length() > 0)
    {
        if(QMessageBox::question(this, tr("确认"), tr("确定要删除选中项吗？")) == QMessageBox::Yes)
        {
            //找到选中项
            QStandardItem* item = this->m_servers.item(indexes[0].row(), 0);
            ModelServer info = item->data(Qt::UserRole).value<ModelServer>();

            //释放内存
            if(this->m_mainWins.contains(info.id))
            {
                delete this->m_mainWins[info.id];
                this->m_mainWins.remove(info.id);
            }
            if(this->m_fileWins.contains(info.id))
            {
                delete this->m_fileWins[info.id];
                this->m_fileWins.remove(info.id);
            }

            this->m_servers.removeRow(indexes[0].row());
            this->saveServers();
        }
    }
}

//打开文件传输窗口
void ServersWindow::on_actionFileTransfer_triggered()
{
    QModelIndexList indexes = ui->lvServers->selectionModel()->selectedIndexes();
    if(indexes.length() > 0)
    {
        QStandardItem* item = this->m_servers.item(indexes[0].row(), 0);
        ModelServer info = item->data(Qt::UserRole).value<ModelServer>();

        if(this->m_fileWins.contains(info.id))
        {
            this->m_fileWins[info.id]->show();
        }
        else
        {
            FileTransferWindow* win = new FileTransferWindow(this);
            this->m_fileWins.insert(info.id, win);
            win->connectToServer(info);
            win->show();
        }
    }
}

